//
//  AddDoorSystemViewController.m
//  RONGAO
//
//  Created by ZhangYeKun on 2017/2/27.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "AddDoorSystemViewController.h"
#import "DSDeviceListContainerView.h"
#import "AddDoorSystemInfoViewController.h"
#import "ConnectDeviceView.h"
#import "DoorSystemModel.h"
#import "ScanViewController.h"
#import "defines.h"
#import "GCDAsyncUdpSocket.h"

#define DISCOVERY_UDP_PORT      9002

@interface AddDoorSystemViewController ()<GCDAsyncUdpSocketDelegate>{
    GCDAsyncUdpSocket *udpSocket;

    BOOL isclick;
}
/** 连接提示 **/
@property(nonatomic,strong) ConnectDeviceView *connectDeviceView;
/** 设备列表containerView **/
@property(nonatomic,strong) DSDeviceListContainerView *containerView;

/** 设备列表 **/
@property(nonatomic,strong) NSMutableArray *device_list;

@end

@implementation AddDoorSystemViewController

static int bLocalSearch = 0;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.device_list = [[NSMutableArray alloc] init];

    [self setNavigationStyle];
    [self masLayoutSubview];
    [self.connectDeviceView setupTipLabel:HAVEWINDOW];

    self.containerView.selectIPCamra = ^(DoorSystemModel *DeviceInfo){
        
        AddDoorSystemInfoViewController *VC = [AddDoorSystemInfoViewController new];
        VC.indexView = self.indexView;
        
        VC.dsModel = DeviceInfo;
        [self.navigationController pushViewController:VC animated:YES];
    };
    [NSThread detachNewThreadSelector:@selector(lanSearch) toTarget:self withObject:nil];
    isclick = NO;
    if (udpSocket == nil)
    {
        [self setupSocket];
    }
    
    if (self.indexView == 0) {
        [self.connectDeviceView setupTipLabel:HAVEWINDOW];
        
    }else if(self.indexView == 1){
        
        [self.connectDeviceView setupTipLabel:NOWINDOW];
        
    }
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
}

- (void)onRightButtonClick:(id)sender{
    
    self.containerView.hidden = NO;
    
    if (isclick == NO) {
        
        [NSThread detachNewThreadSelector:@selector(lanSearch) toTarget:self withObject:nil];
        
        isclick = YES;
        
    }else{
        isclick = NO;

    }
    
    

    
    
}


- (void)lanSearch
{
    if (bLocalSearch == 1) return;
    bLocalSearch = 1;
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.containerView.tableView reloadData];
    });
    
    
    int num = 0;
    int k = 0;
    int cnt = 0;
    [self.device_list removeAllObjects];

#ifdef LIB_140210
    
    while (num == 0 & cnt++ < 2) {
        
#ifdef LIB_140210
        LanSearch_t *pLanSearchAll = [Camera LanSearch:&num timeout:2000];
        printf("camera found(%d)\n", num);
#else
        LanSearch_t *pLanSearchAll = [Camera LanSearch:&num];
        printf("camera found(%d)\n", num);
#endif
        for(k = 0; k < num; k++) {
            
            printf("\tUID[%s]\n", pLanSearchAll[k].UID);
            printf("\tIP[%s]\n", pLanSearchAll[k].IP);
            printf("\tPORT[%d]\n", pLanSearchAll[k].port);
            printf("------------------\n");
            
            DoorSystemModel *dev = [[DoorSystemModel alloc] init];
            dev.uid = [NSString stringWithFormat:@"%s", pLanSearchAll[k].UID];
            dev.ip = [NSString stringWithFormat:@"%s", pLanSearchAll[k].IP];
            dev.port = pLanSearchAll[k].port;
            
            if ([dev.uid isEqualToString:@""]) {
                NSLog(@"dev.uid == NULL");
            } else {
                [self.device_list addObject:dev];
            }
            
            [dev release];
        }
        
        if(pLanSearchAll) {
            free(pLanSearchAll);
        }
    }
#else
    while (num == 0 & cnt++ < 2) {
        
        [device_list removeAllObjects];
        
        struct st_LanSearchInfo *psLanSearchInfo = (struct st_LanSearchInfo *)malloc(sizeof(struct st_LanSearchInfo)*256);
        if(psLanSearchInfo != NULL)
        {
            // wait time 1000 ms to get result, if result is 0 you can extend to 2000 ms
            int num = IOTC_Lan_Search(psLanSearchInfo, 256, 1000);
            printf("IOTC_Lan_Search ret[%d]\n", num);
            for(k=0;k<num;k++)
            {
                printf("UID[%s] Addr[%s:%d]\n", psLanSearchInfo[k].UID, psLanSearchInfo[k].IP, psLanSearchInfo[k].port);
                
                LANSearchDevice *dev = [[LANSearchDevice alloc] initWithLANSearchDeviceType:0];
                dev.uid = [NSString stringWithFormat:@"%s", psLanSearchInfo[k].UID];
                dev.ip = [NSString stringWithFormat:@"%s", psLanSearchInfo[k].IP];
                dev.port = psLanSearchInfo[k].port;
                
                if ([dev.uid isEqualToString:@""]) {
                    NSLog(@"dev.uid == NULL");
                } else {
                    [device_list addObject:dev];
                }
                
                [dev release];
            }
            free(psLanSearchInfo);
        }
        printf("LAN search done...\n");
    }
    
#endif
    
    [self sendSearchBroadcast];
    
    bLocalSearch = 0;
    
    self.containerView.IPcameraDeviceList = [NSMutableArray arrayWithArray:self.device_list];
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.containerView.tableView reloadData];
        
    });
    // [self.tableView reloadData];
    
    
}
#pragma mark udp
- (void)setupSocket
{
    
    return;
    
    // Setup our socket.
    // The socket will invoke our delegate methods using the usual delegate paradigm.
    // However, it will invoke the delegate methods on a specified GCD delegate dispatch queue.
    //
    // Now we can configure the delegate dispatch queues however we want.
    // We could simply use the main dispatc queue, so the delegate methods are invoked on the main thread.
    // Or we could use a dedicated dispatch queue, which could be helpful if we were doing a lot of processing.
    //
    // The best approach for your application will depend upon convenience, requirements and performance.
    //
    // For this simple example, we're just going to use the main thread.
    
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    
    
    NSError *error = nil;
    
    if (![udpSocket enableBroadcast:YES error:&error]) //如果你发送广播，这里必须先enableBroadcast
    {
        NSLog(@"error:%@", error);
        return;
    }
    if (![udpSocket bindToPort:0 error:&error])
    {
        NSLog(@"error:%@", error);
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        NSLog(@"error:%@", error);
        return;
    }
    
}

-(void)sendSearchBroadcast{
    
    return;
    
    NSString* bchost=@"255.255.255.255"; //这里发送广播
    [self sendToUDPServer:@"hello udp" address:bchost port:DISCOVERY_UDP_PORT];
}
-(void)sendToUDPServer:(NSString*) msg address:(NSString*)address port:(int)port{
    /*
     udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; //得到udp util
     NSLog(@"address:%@,port:%d,msg:%@",address,port,msg);
     
     [udpSocket enableBroadcast:YES error:nil]; //如果你发送广播，这里必须先enableBroadcast
     */
    NSData *data=[msg dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:data toHost:address port:port withTimeout:10 tag:1]; //发送udp
}//下面是发送的相关回调函数


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address {
    NSString* rData= [[[NSString alloc] initWithData:address encoding:NSUTF8StringEncoding]
                      autorelease];
    NSLog(@"udpSocket didConnectToAddress:---%@",rData);
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error {
    NSLog(@"udpSocket didNotConnect:---%@",error);
    
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
    NSLog(@"udpSocket didSendDataWithTag:---%ld",tag);
    
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error {
    NSLog(@"udpSocket didNotSendDataWithTag:---tag:%ld  %@", tag, error);
    
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext {
    NSString* rData= [[[NSString alloc] initWithData:address encoding:NSUTF8StringEncoding]
                      autorelease];
    NSLog(@"udpSocket didReceiveData:---%@",rData);
    
    NSString* rData2= [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
                       autorelease];
    NSLog(@"udpSocket didReceiveData:---%@",rData2);
}


- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error {
    NSLog(@"udpSocketDidClose withError:---%@",error);
    
}

- (void)pushCameraVC{
    
    ScanViewController *VC = [[ScanViewController alloc] init];
    VC.indexView = self.indexView;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:YES];
    
}

- (void)pushDSInfoVC{
    
    AddDoorSystemInfoViewController *infoVC = [[AddDoorSystemInfoViewController alloc]init];
    infoVC.indexView = self.indexView;

    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:infoVC animated:YES];
    
}

- (ConnectDeviceView *)connectDeviceView{
    
    if (!_connectDeviceView) {
        
        _connectDeviceView = [[ConnectDeviceView alloc]init];
        
            [self.view addSubview:_connectDeviceView];
        
        
    }
    
    return _connectDeviceView;
    
}

- (DSDeviceListContainerView *)containerView{
    
    if (!_containerView) {
        
        _containerView = [[DSDeviceListContainerView alloc]init];
        [self.view addSubview:_containerView];
        [_containerView.bottomView.leftButton addTarget:self action:@selector(pushDSInfoVC) forControlEvents:UIControlEventTouchDown];
        [_containerView.bottomView.rightButton addTarget:self action:@selector(pushCameraVC) forControlEvents:UIControlEventTouchDown];
        _containerView.hidden = YES;
    }
    
    return _containerView;
    
}


- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"新增门载智能系统" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setRightButtonImage:[UIImage imageNamed:@"icon_refresh_nor"]];
    
}


- (void)masLayoutSubview{
    
    [self.connectDeviceView mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.mas_equalTo(self.view);
        
    }];
    [self.containerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self.view);
        
    }];
    
}

- (void)viewDidUnload
{
    self.device_list = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [_device_list release];
    [udpSocket release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}



@end
